package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumTrackListVo;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Autowired
    private VodService vodService;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    /*
     * 获取声音列表
     * */
    @Override
    public IPage<TrackListVo> getTrackList(Page<TrackListVo> trackListVoPage, TrackInfoQuery trackInfoQuery) {
        return trackInfoMapper.selectTrackList(trackListVoPage, trackInfoQuery);
    }

    /*
     *   上传声音
     * */
    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {
        //  创建上传声音客户端
        VodUploadClient client = new VodUploadClient(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

        //  声音上传临时目录：
        String temPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);

        //  构建上传请求对象
        VodUploadRequest request = new VodUploadRequest();
        //  设置视频本地地址
        request.setMediaFilePath(temPath);

        try {
            VodUploadResponse response = client.upload(vodConstantProperties.getRegion(), request);
            log.info("Upload FileId = {}", response.getFileId());

            HashMap<String, Object> map = new HashMap<>();
            map.put("mediaFileId", response.getFileId());
            map.put("mediaUrl", response.getMediaUrl());

            return map;
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }
        return null;
    }

    /*
     * 保存声音
     * */
    @Override
    public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
        // 初始化 TrackInfo 对象并从 trackInfoVo 对象复制属性
        TrackInfo trackInfo = new TrackInfo();
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        trackInfo.setUserId(userId);

        // 通过专辑ID获取专辑信息，并为新声音设置顺序编号
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfoVo.getAlbumId());
        trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);

        // 从 VOD 服务获取媒体信息并设置声音相关属性
        TrackMediaInfoVo trackMediaInfoVo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());
        trackInfo.setMediaDuration(trackMediaInfoVo.getDuration());
        trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
        trackInfo.setMediaSize(trackMediaInfoVo.getSize());
        trackInfo.setMediaType(trackMediaInfoVo.getType());
        trackInfoMapper.insert(trackInfo);

        this.saveTrackStat(trackInfo.getUserId(), SystemConstant.TRACK_STAT_PLAY);
        this.saveTrackStat(trackInfo.getUserId(), SystemConstant.TRACK_STAT_COLLECT);
        this.saveTrackStat(trackInfo.getUserId(), SystemConstant.TRACK_STAT_PRAISE);
        this.saveTrackStat(trackInfo.getUserId(), SystemConstant.TRACK_STAT_COMMENT);
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);

        // 更新专辑信息
        this.albumInfoMapper.updateById(albumInfo);

    }

    private void saveTrackStat(Long trackId, String statPlay) {
        TrackStat trackStat = new TrackStat();
        trackStat.setTrackId(trackId);
        trackStat.setStatType(statPlay);
        trackStat.setStatNum(0);
        trackStatMapper.insert(trackStat);
    }

    /*
     * 删除声音
     * */
    @Override
    public void deleteTrackInfoById(Long trackId) {

        TrackInfo trackInfo = this.trackInfoMapper.selectById(trackId);
        trackInfoMapper.deleteById(trackId);


        trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, trackId));

        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);

        albumInfoMapper.updateById(albumInfo);

        trackInfoMapper.updateOrderNum(trackInfo.getOrderNum(), trackInfo.getAlbumId());

        vodService.deleteMedia(trackInfo.getMediaFileId());
    }

    /*
     * 修改声音
     * */
    @Override
    public void updateTrackInfo(Long trackId, TrackInfoVo trackInfoVo) {

        TrackInfo trackInfo = this.getById(trackId);
        String mediaFileId = trackInfo.getMediaFileId();
        BeanUtils.copyProperties(trackInfoVo, trackInfo);

        if (!mediaFileId.equals(trackInfoVo.getMediaFileId())) {
            vodService.deleteMedia(mediaFileId);

            TrackMediaInfoVo mediaInfo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());
            trackInfo.setMediaUrl(mediaInfo.getMediaUrl());
            trackInfo.setMediaSize(mediaInfo.getSize());
            trackInfo.setMediaDuration(mediaInfo.getDuration());
            trackInfo.setMediaType(mediaInfo.getType());
        }
        trackInfoMapper.updateById(trackInfo);
    }

    /*
     * 根据专辑id获取声音分页列表
     * */
    @Override
    public IPage<AlbumTrackListVo> getTrackPageList(Page<AlbumTrackListVo> trackListVoPage, Long albumId, Long userId) {
        //根据专辑id查询声音
        IPage<AlbumTrackListVo> albumTrackListVoIPage = trackInfoMapper.getTrackInfoList(trackListVoPage, albumId);

        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        //未登录
        if (null == userId) {
            //需要付费
            if (!SystemConstant.ALBUM_PAY_TYPE_FREE.equals(albumInfo.getPayType())) {
                // 免费试听的集数
                Integer tracksForFree = albumInfo.getTracksForFree();
                //拿到所有专辑声音列表
                for (AlbumTrackListVo allAlbumTrackListVo : albumTrackListVoIPage.getRecords()) {
                    // 大于免费试听的集数，显示付费标识
                    if (allAlbumTrackListVo.getOrderNum() > tracksForFree) {
                        // 设置显示付费标识
                        allAlbumTrackListVo.setIsShowPaidMark(true);
                    }
                }
                return albumTrackListVoIPage;
            }
        } else {
            Boolean isNeedPaidMark = false;
            // 已登录判断是否是VIP
            if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(albumInfo.getPayType())) {
                Result<UserInfoVo> userInfoResult = userInfoFeignClient.getUserInfo(userId);
                Assert.notNull(userInfoResult, "用户信息为空");
                UserInfoVo userInfoVo = userInfoResult.getData();
                //不是vip
                if ((userInfoVo.getIsVip() == 0) || (userInfoVo.getIsVip() == 1 && userInfoVo.getVipExpireTime().before(new Date()))) {
                    isNeedPaidMark = true;
                }
            } else if (SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(albumInfo.getPayType())) {
                isNeedPaidMark = true;
            }
            if (isNeedPaidMark){
                // 拿到所有需要付费专辑声音列表
                List<AlbumTrackListVo> needPaidTrackList = albumTrackListVoIPage.getRecords().stream().filter(albumTrackListVo -> albumTrackListVo.getOrderNum() > albumInfo.getTracksForFree()).collect(Collectors.toList());
               // 所有需要付费的专辑声音id集合
                List<Long> needPaidTrackIdList = needPaidTrackList.stream().map(albumTrackListVo -> albumTrackListVo.getTrackId()).collect(Collectors.toList());
                Result<Map<Long, Integer>> mapResult = userInfoFeignClient.userIsPaidTrack(albumId, needPaidTrackIdList);
                Assert.notNull(mapResult, "付费标识查询失败");
                //付费声音ID map   key=trackld value=1
                Map<Long, Integer> map = mapResult.getData();

                for (AlbumTrackListVo albumTrackListVo : needPaidTrackList) {
                    albumTrackListVo.setIsShowPaidMark(map.get(albumTrackListVo.getTrackId()) == 0);
                }
            }

        }
        return albumTrackListVoIPage;
    }
}
